package tech.soulcoder.时间服务器;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author admin
 */
public class TimeServer {
    public void bind(int port) throws Exception {
        System.out.println("服务端开始绑定端口 " +port);
        // 配置服务端线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 启动netty 的辅助类
            ServerBootstrap b = new ServerBootstrap();
            // 父子线程组传入
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel){
                            // 配置消息 解码
                            socketChannel.pipeline().addLast(new TimeServerHandler());

                        }
                    });
            // 配置完基本信息 后  开始端口监听
            ChannelFuture future = b.bind(port).sync();
            System.out.println("初始化成功....." +port);
            // 阻塞 的带服务 端链路 关闭后退出
            future.channel().closeFuture().sync();
        } finally {
            // 优雅关机
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new TimeServer().bind(10004);
    }

}
